package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.IdGenTagEnum;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.mapper.OrderGoodsMapper;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.dto.CustomerChgOrderGoodsDto;
import com.weixing.mall.provider.model.vo.FrontOrderGoodsVo;
import com.weixing.mall.provider.model.vo.OrderGoodsVo;
import com.weixing.mall.provider.service.IOrderGoodsService;
import com.weixing.mall.util.ListUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName OrderGoodsServiceImpl
 * @Description
 * @Author Small
 * @Date 2020/1/10 11:59
 * @Version 1.0
 **/
@Service
public class OrderGoodsServiceImpl extends ServiceImpl<OrderGoodsMapper, OrderGoods> implements IOrderGoodsService {
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Long getProductId(String productSkuDesp, Long goodsId) {
        return baseMapper.getProductId(productSkuDesp, goodsId);
    }

    @Override
    public void customerChgOrder(CustomerChgOrderGoodsDto customerChgOrderGoodsDto) {
        baseMapper.customerChgOrder(customerChgOrderGoodsDto);
    }

    @Override
    public FrontOrderGoodsVo selectByOrderId(Long id) {
        OrderGoodsVo orderGoods =orderGoodsMapper.findByOrderId(id);
        FrontOrderGoodsVo vo = new FrontOrderGoodsVo();
        if (null != orderGoods) {
            BeanUtils.copyProperties(orderGoods, vo);
        }
        return vo;
    }

    @Override
    public void chgGoodsProductId(Long id, Long priductId) {
        baseMapper.chgGoodsProductId(id, priductId);
    }

    @Override
    public List<FrontOrderGoodsVo> selectFrontOrderGoodsVoByOrderId(Long orderId) {
        return baseMapper.selectFrontOrderGoodsVoByOrderId(orderId);
    }

    @Override
    public OrderGoodsVo findByOrderId(Long orderId) {
        return orderGoodsMapper.findByOrderId(orderId);
    }

    @Override
    public List<OrderGoods> selectByOrderStatus(Integer orderStatus,Integer orderType,Long [] ids) {
        orderType=orderType.equals(OrderTypeEnum.ALL.getValue())?null:orderType;
        //根据订单的状态和类型查询所有待封单的信息 或者已封单的模糊匹配订单
       /* ids=null;
        List<Order> ordersList=orderGoodsMapper.selectByOrderStatus(orderStatus, SealMatchRuleEnum.RULE3.getValue(),orderType,ids);
        List<Long> productList = ordersList.stream().map(Order -> Order.getId()).collect(Collectors.toList());*/
        List<Long> productList= Arrays.asList(ids);
        List<OrderGoods> orderGoodsList = Lists.newArrayList();
        if(productList.size() > 0){
            //通过订单ID信息查询订单商品，这样做的目的是为了防止order分表导致查询资源的消耗过多。
            List<List<Long>>  productLsits= ListUtil.fixedGrouping(productList,100);//防止路径过长
            for(List<Long> longs:productLsits){
                orderGoodsList.addAll(baseMapper.selectList(new QueryWrapper<OrderGoods>().in("order_id", longs)));
            }
            return orderGoodsList;
        }
        return  orderGoodsList;
    }

    @Override
    public OrderGoods getByOrderId(Long orderId) {
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<OrderGoods>().eq("order_id",orderId);
        return getOne(wrapper);
    }

    @Override
    public void updateGoodsTag(List<Long> orderList){
        orderList.forEach(orderId->{
            UpdateWrapper uw = new UpdateWrapper();
            uw.eq("order_id",orderId);
            uw.set("updated_time",new Date());
            uw.set("goods_tag",getGoodsTag(GlobalConstant.ORDER_GOODS_TAG));
            update(uw);
        });
    }

    /**
     * 方法描述:  货物标识自增序列号
     * @return java.lang.Long
     */
    public String getGoodsTag(String prefix) {
        long liveTime = 86400L;
        String dateFmt = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String key = IdGenTagEnum.GOODS_TAG.getValue() + dateFmt;
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        //初始设置过期时间
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return prefix+dateFmt+parseTransNo(increment + 1,5);
    }

    private static String parseTransNo(Long tNo, int len) {
        String transNo = String.valueOf(tNo);
        return transNo.length() < len ? String.format("%05d", tNo) : transNo;
    }
}
